package com.xiecong.controller;


import com.alibaba.excel.EasyExcel;
import com.xiecong.aspect.annotation.LogOperation;
import com.xiecong.excel.StudentModel;
import com.xiecong.excel.StudentReaderListener;
import com.xiecong.pojo.PageResult;
import com.xiecong.pojo.Result;
import com.xiecong.pojo.Student;
import com.xiecong.pojo.StudentQueryParam;
import com.xiecong.service.StudentService;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

@Slf4j
@RestController
@Valid
@RequestMapping("/students")
public class StudentController {

    @Autowired
    private StudentService studentService;

    /**
     * 分页查询学生列表
     */
    @GetMapping
    public Result pageQuery(StudentQueryParam studentQueryParam) {
        log.info("查询所有学生列表{}", studentQueryParam);
        PageResult<Student> pageQueryList = studentService.pageQuery(studentQueryParam);
        return Result.success(pageQueryList);
    }


    /**
     * 添加学生
     */
    @PostMapping
    @LogOperation
    public Result add(@RequestBody Student student){
        studentService.add(student);
        return Result.success();
    }


    /**
     * 修改学生信息-数据回显-根据id查询
     */
    @GetMapping("/{id}")
    public Result findById(@PathVariable Integer id){
        Student student = studentService.findById(id);
        return Result.success(student);
    }


    /**
     * 修改学生信息
     */
    @PutMapping
    @LogOperation
    public Result update(@RequestBody Student student){
        studentService.update(student);
        return Result.success();
    }


    /**
     * 删除学生信息（单条或批量）
     */
    @DeleteMapping("/{ids}")
    @LogOperation
    public Result deleteByIds(@PathVariable List<Integer> ids){
        studentService.deleteByIds(ids);
        return Result.success();
    }


    /**
     * 违纪处理
     */
     @PutMapping("/violation/{id}/{score}")
    public Result violationHandle(@PathVariable Integer id,@PathVariable Integer score){
         studentService.violationHandle(id,score);
         return Result.success();
     }


    /**
     * 批量导入
     */
    @PostMapping("/import/{clazzId}")
    public Result importExcel(@PathVariable Integer clazzId, MultipartFile file) throws IOException {
        //EasyExcel封装的方法
        EasyExcel.read(file.getInputStream(), //文件的输入流
                        StudentModel.class, // 解析每行数据，映射成实体类
                        new StudentReaderListener(studentService,clazzId)// 读取数据的处理器 事件监听
                )
                .sheet().doRead();
        return Result.success();
    }

}
